package com.example.redisSimple.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.example.redisSimple.entity.Commodity;
import com.example.redisSimple.server.CommodityService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * TestLockController
 *
 * @ClassName TestLockController
 * @Author lixingxing
 * @Date 2021/08/09 下午 13:40
 * @Version 1.0
 */
@Slf4j
@RestController
public class TestLockController {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private CommodityService commodityService;

    private static final String LOCK_KEY = "commodity_key";

    // 抢购商品
    @RequestMapping("/buy/{id}")
    public void buyingCommodity(@PathVariable("id") Integer id) {
        RLock lock = redissonClient.getLock(LOCK_KEY);
        lock.lock();
        InventoryHandling(id);
        lock.unlock();
    }

    /**
     * 库存处理
     */
    public void InventoryHandling (Integer id) {
        Wrapper wrapper = new EntityWrapper();
        try {
            Commodity commodity = commodityService.selectOne(wrapper.eq("id",id));
            Integer commodityNum = commodity.getCommodityNum();
            if (commodityNum > 0) {
                commodity.setCommodityNum(commodityNum - 1);
                boolean b = commodityService.updateById(commodity);
                if (b) {
                   log.info("抢购成功！");
                } else {
                    // 重试机制

                }
            } else {
                throw new RuntimeException("库存不足");
            }

            // 记录卖掉的商品
            Wrapper wrapper2 = new EntityWrapper();
            Commodity commoditylog = commodityService.selectOne(wrapper2.eq("id",2));
            if (commoditylog == null) {
                commoditylog = new Commodity();
                commoditylog.setId(2);
                commoditylog.setCommodityNum(1);
                commodityService.insert(commoditylog);
            } else {
                commoditylog.setId(2);
                commoditylog.setCommodityNum(commoditylog.getCommodityNum()+1);
                commodityService.updateById(commoditylog);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }


}
